#!/usr/bin/env python3
# @Date    : 2020-07-16
# @Author  : Bright Li (brt2@qq.com)
# @Link    : https://gitee.com/brt2

# from tornado.web import Application, RequestHandler, StaticFileHandler
from tornado.ioloop import IOLoop
from tornado.options import define, options, parse_command_line
# from tornado.httpserver import HTTPServer

import pyrestful.rest
from pyrestful import mediatypes
from pyrestful.rest import get, post

import os.path
import watermark

define("port", default=10110, help="默认端口10110")

RECV_FILES = []

# 视图类
class IndexHandler(pyrestful.rest.RestHandler):
    dir_posted = "data/posted"
    dir_copyright = "data/created"

    @get(_path="/", _produces=mediatypes.APPLICATION_JSON)
    def homepage(self):
        global RECV_FILES

        RECV_FILES = []
        self.render("index.html")

    @get(_path="/data/created/{filename}")
    def get_image(self, filename):
        """ 获取加密后的图像 """
        path_file = "data/created/" + filename
        self.set_header ('Content-Type', 'application/octet-stream')
        self.set_header ('Content-Disposition', 'attachment; filename='+path_file)
        with open(path_file, 'rb') as f:
            self.write(f.read())
        self.finish()

    @post(_path="/img", _produces=mediatypes.APPLICATION_JSON)
    def post_img(self):
        global RECV_FILES
        RECV_FILES = self.request.files["file"]
        return {}

    @post(_path="/form", _produces=mediatypes.APPLICATION_JSON)
    def post_form(self, *args, **kargs):
        """ 接收表单信息
            return {"filename.jpg": {"status": True, "path": "data/xxx.jpg"}, ...}
        """
        # print(">>>", args, kargs)
        # print("<<<", self.request.arguments,
        #              self.request.query_arguments,
        #              self.request.body_arguments,
        #              self.request.headers,
        #              self.request.body,
        #              self.request.query,
        #              self.request.remote_ip,
        #              self.request.cookies)
        global RECV_FILES

        if not RECV_FILES:
            return

        wm_content = self.request.body_arguments["content"][0].decode()
        isBlind = self.request.body_arguments["wm_type"][0] == b"1"

        dict_ret = {}
        for dict_file in RECV_FILES:
            # type_ = dict_file["content_type"]  # 'image/jpeg'
            filename = dict_file["filename"]
            path_save = os.path.join(self.dir_posted, filename)
            # if os.path.exists(path_save):
            #     dict_ret = {
            #         "status": False,
            #         "reason": "文件已存在"
            #     }
            #     continue

            # 存储原图像
            with open(path_save, 'wb') as fp:
                fp.write(dict_file["body"])

            path_watermark = self.make_watermark(path_save, wm_content, isBlind)
            dict_ret = {
                "status": True,
                "url"   : path_watermark
            }
        RECV_FILES = []
        return dict_ret

    def make_watermark(self, path_img, text, isBlind=False):
        """ return a new img with mark """
        func_wm = watermark.paste_bwm if isBlind else watermark.paste_text

        filename = os.path.basename(path_img)
        path_watermark = os.path.join(self.dir_copyright, filename)

        func_wm(path_img, text, path_watermark)
        return path_watermark


if __name__ == '__main__':

    parse_command_line()
    app = pyrestful.rest.RestService([
            IndexHandler,
        ],

        # 网页模板
        template_path="templates",
        # 静态文件
        static_path="static",
        # static_url_prefix="/static",  # 添加后，link正常，scripts脚本路径报错
        debug=True,
        compiled_template_cache=False
    )
    app.listen(options.port)
    # server = HTTPServer(app)
    # server.listen(options.port)
    IOLoop.current().start()
